package cn.lyh.controller;

import cn.lyh.config.FileConfig;
import cn.lyh.entity.File;
import cn.lyh.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;


@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Resource
    private FileService fileService;

    @Resource
    private FileConfig fileConfig;
    @PostMapping("/upload")
    public String upload(HttpServletRequest request) throws Exception{
        // 获取请求头的文件信息
        MultipartHttpServletRequest multipartHttpServletRequest = null;
        try {
            multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        } catch (Exception e) {
            log.error("获取文件信息出现错误");
            throw new Exception("GET_FILE_ERROR获取文件信息出现错误");
        }
        MultipartFile file = multipartHttpServletRequest.getFile("file");
        String fileId = fileService.upload(file);
        return fileId;
    }

    @GetMapping("/download/{fileId}")
    public void download(@PathVariable @NotNull String fileId, HttpServletResponse response) throws Exception {
        // 以流的形式下载文件。
        File fileInfo = fileService.getById(fileId);
        InputStream in = null;
        OutputStream os = null;
        try {
            java.io.File file = new java.io.File(fileInfo.getAddress());
            in = new BufferedInputStream(new FileInputStream(fileInfo.getAddress()));
            int count = 0;
            while (count == 0) {
                count = in.available();
            }
            byte[] buffer = new byte[count];
            in.read(buffer);
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileInfo.getOriginalName());
            response.addHeader("Content-Length", "" + file.length());
            response.setCharacterEncoding("utf-8");
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            os.write(buffer);
            os.flush();
        } catch (Exception ex) {
            log.error("文件下载失败，异常信息=[{}]", ex);
            ex.printStackTrace();
            PrintWriter writer = response.getWriter();
            writer.println("410");
            writer.flush();
            writer.close();
        } finally {
            in.close();
            os.close();
        }
    }


    @GetMapping("/get/{fileId}")
    public File getById(@PathVariable String fileId){
        return fileService.getById(fileId);
    }


}
